package cn.ecnu.user.handler;

import cn.ecnu.common.Constant;
import cn.ecnu.exception.RRXException;
import cn.ecnu.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;
import java.util.HashMap;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RRXException.class)
    public R handleJwtException(RRXException e) {
        return R.error(e.getCode(), e.getMessage());
    }

    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> error = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError -> {
            error.put(fieldError.getField(), fieldError.getDefaultMessage());
        }));
        return R.error(Constant.ARGUMENT_INVALID.getCode(), Constant.ARGUMENT_INVALID.getMsg()).put("data", error);
    }

    @ExceptionHandler(ServletException.class)
    public R handlerServletException(ServletException e) {
        return R.error(Constant.SERVLET_ERROR.getCode(), Constant.SERVLET_ERROR.getMsg() + ": " + e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        return R.error();
    }
}
